package ai.zixing.mashibing.basic_class.class02;

import java.util.LinkedList;
import java.util.Queue;

// 队列实现栈
// 类似于复制算法
public class Code07_TwoQueueImplementStack {
    public static void main(String[] args) {
        TwoQueueStack<Integer> stack = new TwoQueueStack<>();

    }

    public static class TwoQueueStack<T>{
        public Queue<T> queue;
        public Queue<T> help;

        public TwoQueueStack() {
            queue = new LinkedList<>();
            help = new LinkedList<>();
        }

        public void push(T value) {
            queue.offer(value);
        }

        public T poll() {
            // 留一个，将其他的放入 help 中
            while (queue.size() > 1) {
                help.offer(queue.poll());
            }
            // 将第一个添加的元素取出
            T ans = queue.poll();
            // 交换复原
            Queue<T> temp = queue;
            queue = help;
            help = temp;
            return ans;
        }

        public T peek() {
            while (queue.size() > 1) {
                help.offer(queue.poll());
            }
            T ans = queue.peek();
            Queue<T> temp = queue;
            queue = help;
            help = temp;
            help.offer(ans);
            return ans;
        }
    }
}
